package com.lightsaber.trade.as.web.device;

import java.util.List;

import org.apache.struts2.convention.annotation.Namespace;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.utils.web.struts2.Struts2Utils;

import com.lightsaber.trade.as.entity.device.CommandPublishToDevice;
import com.lightsaber.trade.as.service.device.CommandPublishToDeviceManager;
import com.lightsaber.trade.as.service.device.InfoCollectForDeviceManager;
import com.lightsaber.trade.core.web.BaseAction;

@Namespace("/device")
public class CommandPublishToDeviceAction extends BaseAction {

    private static final long serialVersionUID = 7918485268921396640L;

    @Autowired
    private transient CommandPublishToDeviceManager dommandPublishToDeviceManager;
    @Autowired
    private transient InfoCollectForDeviceManager infoCollectForDeviceManager;

    private String deviceId;
    private long timeOut;
    private String content;

    private CommandPublishToDevice commandPublishToDevice;

    @Override
    public String execute() throws Exception {
        return SUCCESS;
    }

    public String iframe() throws Exception {
        return "iframe";
    }

    public void save() throws Exception {
        try {
            dommandPublishToDeviceManager.save(deviceId, content);

            Struts2Utils.renderText("OK");

        } catch (Exception e) {
            Struts2Utils.renderJson("NO");
        }
    }

    public void receive() throws InterruptedException {
        List<String> infoList = null;

        infoList = infoCollectForDeviceManager.findNoReadInfo(deviceId);

        long limit = System.currentTimeMillis() + timeOut;

        while (System.currentTimeMillis() < limit) {

            infoList = infoCollectForDeviceManager.findNoReadInfo(deviceId);

            if (infoList.size() > 0) {
                break;
            } else {
                Thread.sleep(4000L);
            }
        }

        Struts2Utils.renderJson(infoList);
    }

    // ----------------Bean-----------------
    public String getDeviceId() {
        return deviceId;
    }

    public void setDeviceId(String deviceId) {
        this.deviceId = deviceId;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public CommandPublishToDevice getCommandPublishToDevice() {
        return commandPublishToDevice;
    }

    public void setCommandPublishToDevice(CommandPublishToDevice commandPublishToDevice) {
        this.commandPublishToDevice = commandPublishToDevice;
    }

    public long getTimeOut() {
        return timeOut;
    }

    public void setTimeOut(long timeOut) {
        this.timeOut = timeOut;
    }

}
